#include <usbdev.h>

extern "C"{
#include <hidsdi.h>
#include <setupapi.h>
}

void CloseHid(HANDLE hdev){
    if(hdev!=INVALID_HANDLE_VALUE){
	CloseHandle(hdev);
    }
}

HANDLE OpenHid(LPTHREAD_START_ROUTINE thread){
    GUID				guid;
    HDEVINFO				info;
    int					i;
    DWORD				n;
    SP_DEVICE_INTERFACE_DATA		dat;
    SP_DEVICE_INTERFACE_DETAIL_DATA	*detail;
    HANDLE				res;
    HIDD_ATTRIBUTES			attr;

    res=INVALID_HANDLE_VALUE;
    HidD_GetHidGuid(&guid);
    info=SetupDiGetClassDevs(&guid,NULL,NULL,
	DIGCF_PRESENT|DIGCF_INTERFACEDEVICE);
    if(info==INVALID_HANDLE_VALUE)
	return INVALID_HANDLE_VALUE;

    dat.cbSize=sizeof(dat);
    for(i=0;SetupDiEnumDeviceInterfaces(info,NULL,&guid,i,&dat);i++){
	SetupDiGetDeviceInterfaceDetail(info,&dat,NULL,0,&n,NULL);
	if(detail=(PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LMEM_FIXED,n)){
	    detail->cbSize=sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
	    SetupDiGetDeviceInterfaceDetail(info,&dat,detail,n,&n,NULL);
	    res=CreateFile(detail->DevicePath,GENERIC_READ|GENERIC_WRITE,
		FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,
		FILE_FLAG_OVERLAPPED,NULL);
	    if(res!=INVALID_HANDLE_VALUE){
		attr.Size=sizeof(attr);
		HidD_GetAttributes(res,&attr);
		if((attr.VendorID==HID_VENDOR)&&(attr.ProductID==HID_PRODUCT)){
		    if(thread)
			CloseHandle(CreateThread(NULL,0,thread,res,0,&n));
		    LocalFree(detail);
		    break;
		}
		CloseHandle(res);
		res=INVALID_HANDLE_VALUE;
	    }
	    LocalFree(detail);
	}
	dat.cbSize=sizeof(dat);
    }	
    SetupDiDestroyDeviceInfoList(info);
    return res;
}